from datetime import datetime

from sqlalchemy import (
    Column,
    Integer,
    String,
    Boolean,
    DateTime,
    Table,
    Float,
    Text, ForeignKey, MetaData
)
from sqlalchemy.orm import relationship
from exts import Engine, Base, metadata, session


class Delete:
    yes = 1  # 不显示
    no = 0  # 显示


class User(Base):
    # 命名表名
    __tablename__ = 't_user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(32), unique=True, nullable=False)
    password = Column(String(200), nullable=False)
    phone = Column(String(11), nullable=True)
    email = Column(String(30))
    icon = Column(String(100))
    isdelete = Column(Boolean, default=Delete.yes)
    createTime = Column(DateTime, default=datetime.now)

    def __str__(self):
        return self.username


class Files(Base):
    __tablename__ = 't_pic'
    id = Column(Integer, primary_key=True, autoincrement=True)
    filename = Column(String(50))
    path = Column(String(200))


class Login_log(Base):
    __tablename__ = 't_login_log'
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), default=None)
    ip = Column(String(50), default=None)
    login_time = Column(DateTime, default=None)


class Role_User(Base):
    __tablename__ = 't_role_user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    role_id = Column(Integer, ForeignKey('t_role.id'), primary_key=True)
    user_id = Column(Integer, ForeignKey('t_user.id'), primary_key=True)


class Permission:
    """
    1:访问者 ：可以修改个人信息
    23:运营：管理帖子，评论，前台用户
    63:管理员：拥有本系统所有权限
    255:开发者：开发人员专用
    """
    ALL_PERMISSION = 0b11111111 # 255
    # 访问者权限
    VISITOR = 0b00000001  # 1
    # 管理帖子权限
    POSTER = 0b00000010 # 2
    # 管理评论权限
    COMMENTER = 0b00000100 # 4
    # 管理模块的权限
    BOARDER = 0b00001000 # 8
    # 管理前台用户的权限
    FONTUSER = 0b00010000 # 16
    # 管理后台用户的权限
    BACKENDUSER = 0b00100000 #32
    # 后台管理员权限
    ADMIN = 0b01000000 # 64


class Role(Base):
    __tablename__ = 't_role'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32), unique=True, nullable=False)
    desc = Column(String(200), nullable=True)
    createTime = Column(DateTime, default=datetime.now)
    permissions = Column(Integer, default=Permission.VISITOR)
    user_to_role = relationship('User', secondary='t_role_user', backref='user_to_role')

    def init_role(self):
        role_name_list = ['visitor', 'operator', 'admin', 'developer']
        roles_permissions_map = {
            'visitor': [Permission.VISITOR],
            'operator': [Permission.POSTER, Permission.COMMENTER,
                         Permission.BOARDER, Permission.FONTUSER,
                         Permission.BACKENDUSER
                         ],
            'admin': [Permission.ALL_PERMISSION]
        }
        try:
            for role_name in role_name_list:
                role = Role.query.filter_by(name=role_name).first()
                if not role:
                    role = Role(name=role_name)
                role.reset_permissions()
                for permission in roles_permissions_map[role_name]:
                    role.add_permission(permission)
                    session.add(role)
                    session.commit()
        except:
            session.rollback()

        session.close()

    def reset_permissions(self):
        self.permissions = 0

    def has_permission(self, permission):
        return self.permissions & permission == permission

    def add_permission(self, permission):
        if not self.has_permission(permission):
            self.permissions += permission
